package com.example.administrator.szb.xzyw;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.LoginNewActivity;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.SQYWBean;
import com.example.administrator.szb.bean.YWBDBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.Toasts;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/10/12.
 */

public class GPZYActivity extends BaseActivity {
    @Bind(R.id.tjzl_edit_gpdm)
    EditText tjzlEditGpdm;
    @Bind(R.id.tjzl_ll_gpdm)
    LinearLayout tjzlLlGpdm;
    @Bind(R.id.tjzl_text_gpsx)
    TextView tjzlTextGpsx;
    @Bind(R.id.tjzl_ll_gpsx)
    LinearLayout tjzlLlGpsx;
    @Bind(R.id.tjzl_text_sssc)
    TextView tjzlTextSssc;
    @Bind(R.id.tjzl_ll_sssc)
    LinearLayout tjzlLlSssc;
    @Bind(R.id.tjzl_text_sshy)
    TextView tjzlTextSshy;
    @Bind(R.id.tjzl_ll_sshy)
    LinearLayout tjzlLlSshy;
    @Bind(R.id.tjzl_text_fmxx)
    TextView tjzlTextFmxx;
    @Bind(R.id.tjzl_ll_fmxx)
    LinearLayout tjzlLlFmxx;
    @Bind(R.id.tjzl_edit_zygs)
    EditText tjzlEditZygs;
    @Bind(R.id.tjzl_ll_zygs)
    LinearLayout tjzlLlZygs;
    @Bind(R.id.tjzl_edit_rzje)
    EditText tjzlEditRzje;
    @Bind(R.id.tjzl_ll_rzje)
    LinearLayout tjzlLlRzje;
    @Bind(R.id.textView73)
    TextView textView73;
    @Bind(R.id.tjzl_edit_zkl)
    EditText tjzlEditZkl;
    @Bind(R.id.tjzl_ll_zkl)
    LinearLayout tjzlLlZkl;
    @Bind(R.id.tjzl_text_fksj)
    TextView tjzlTextFksj;
    @Bind(R.id.tjzl_ll_fksj)
    LinearLayout tjzlLlFksj;
    @Bind(R.id.tjzl_edit_rzqx)
    EditText tjzlEditRzqx;
    @Bind(R.id.tjzl_ll_rzqx)
    LinearLayout tjzlLlRzqx;
    @Bind(R.id.tjzl_edit_llyq)
    EditText tjzlEditLlyq;
    @Bind(R.id.tjzl_ll_llyq)
    LinearLayout tjzlLlLlyq;
    @Bind(R.id.tjzl_edit_lxr)
    EditText tjzlEditLxr;
    @Bind(R.id.tjzl_ll_lxr)
    LinearLayout tjzlLlLxr;
    @Bind(R.id.tjzl_edit_lxfs)
    EditText tjzlEditLxfs;
    @Bind(R.id.tjzl_ll_lxfs)
    LinearLayout tjzlLlLxfs;
    @Bind(R.id.tjzl_edit_yq)
    EditText tjzlEditYq;
    @Bind(R.id.tjzl_test_zs)
    TextView tjzlTestZs;
    @Bind(R.id.tjzl_button_tj)
    Button tjzlButtonTj;
    @Bind(R.id.tjzl_text_bmxy)
    TextView tjzlTextBmxy;

    private TimePickerView  pvCustomTime;
    private int counselor_id = 0;
    YWBDBean ywbdBean;
    ArrayList<String> info = new ArrayList<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gpzy_activity);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        requestData(getIntent().getIntExtra("id",-1));
        initToolbar(R.id.gpzy_toolbar_include, "股票质押");
        initCustomTimePicker();//初始化时间选择器
        editListenter(tjzlEditYq,tjzlTestZs);//设置字数监听
        hasIntent();
    }
    private void hasIntent() {
        counselor_id = getIntent().getIntExtra("counselor_id",0);
    }

    private void requestData(int id) {
        HashMap<String,String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("business_id",id+"");
        map.put("counselor_id",counselor_id+"");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, YWBDBean.class, URLAddress.URLBASE + URLAddress.URL_BDYW, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ywbdBean = (YWBDBean) response;
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
            }
        });
    }

    private void initCustomTimePicker() {

        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DATE));
        Calendar endDate = Calendar.getInstance();
        endDate.set(startDate.get(Calendar.YEAR)+5, 11, 31);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tjzlTextFksj.setTextColor(getResources().getColor(R.color.toolbar_home));
                tjzlTextFksj.setText(getTime(date));
            }
        })
                /*.setType(TimePickerView.Type.ALL)//default is all
                .setCancelText("Cancel")
                .setSubmitText("Sure")
                .setContentSize(18)
                .setTitleSize(20)
                .setTitleText("Title")
                .setTitleColor(Color.BLACK)
               /*.setDividerColor(Color.WHITE)//设置分割线的颜色
                .setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
                .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                .setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
                .setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
                .setSubmitColor(Color.WHITE)
                .setCancelColor(Color.WHITE)*/
               /*.gravity(Gravity.RIGHT)// default is center*/
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年","月","日","","","")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .build();

    }


    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @OnClick({R.id.tjzl_ll_gpdm, R.id.tjzl_ll_gpsx, R.id.tjzl_ll_sssc, R.id.tjzl_ll_sshy, R.id.tjzl_ll_fmxx, R.id.tjzl_ll_zygs, R.id.tjzl_ll_rzje, R.id.tjzl_ll_zkl, R.id.tjzl_text_fksj, R.id.tjzl_ll_fksj, R.id.tjzl_ll_rzqx, R.id.tjzl_ll_llyq, R.id.tjzl_ll_lxr, R.id.tjzl_ll_lxfs, R.id.tjzl_button_tj, R.id.tjzl_text_bmxy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tjzl_ll_gpdm:
                break;
            case R.id.tjzl_ll_gpsx:
                yw_ci_show(1);
                break;
            case R.id.tjzl_ll_sssc:
                yw_ci_show(2);
                break;
            case R.id.tjzl_ll_sshy:
                yw_ci_show(3);
                break;
            case R.id.tjzl_ll_fmxx:
                yw_ci_show(4);
                break;
            case R.id.tjzl_ll_zygs:
                break;
            case R.id.tjzl_ll_rzje:
                break;
            case R.id.tjzl_ll_zkl:
                break;
            case R.id.tjzl_text_fksj:
                pvCustomTime.show(); //弹出自定义时间选择器
                break;
            case R.id.tjzl_ll_fksj:
                break;
            case R.id.tjzl_ll_rzqx:
                break;
            case R.id.tjzl_ll_llyq:
                break;
            case R.id.tjzl_ll_lxr:
                break;
            case R.id.tjzl_ll_lxfs:
                break;
            case R.id.tjzl_button_tj:
                if (SampleApplicationLike.getUserloginInstance().getId()<=0) {
                    startActivity(new Intent(this, LoginNewActivity.class));
                }else{
                    requestSubmitData();
                }
                break;
            case R.id.tjzl_text_bmxy:
                break;
        }
    }

    private void requestSubmitData() {
        boolean flag = checkInfo();
        if (flag) {
            doSubmit();
        }else{

        }
    }

    private void doSubmit() {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("business_id",getIntent().getIntExtra("id",-1)+"");
        map.put("counselor_id",counselor_id+"");
        map.put("users_id",""+SampleApplicationLike.getUserloginInstance().getId());//测试
        map.put("namelink",info.get(info.size()-3)+"");
        map.put("tel",info.get(info.size()-2)+"");
        map.put("content",info.get(info.size()-1)+"");

        for (int i = 0; i < ywbdBean.getData().getBusField().size(); i++) {
            map.put(""+ywbdBean.getData().getBusField().get(i).getId(),info.get(i));
        }

        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, SQYWBean.class, URLAddress.URLBASE + URLAddress.URL_SUBMINT_BDYW, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                if (((SQYWBean)response).getResult() != 1){
                    Toasts.show(GPZYActivity.this, ""+((SQYWBean)response).getErr_msg(), Toast.LENGTH_SHORT);
                }else{
                    startActivity(new Intent(GPZYActivity.this,SuccessActivity.class));
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
            }
        });
    }

    private boolean checkInfo() {
        getInfo();
        return true;
    }

    private void getInfo() {
        info.clear();
        info.add(tjzlEditGpdm.getText().toString().trim());

        if (TextUtils.isEmpty(tjzlTextGpsx.getText().toString())) {
            info.add("");
        } else {
            for (int i = 0; i < ywbdBean.getData().getBusField().get(1).getBuschoices().size(); i++) {
                if (ywbdBean.getData().getBusField().get(1).getBuschoices().get(i).getTitle().equals(tjzlTextGpsx.getText().toString())) {
                    info.add(ywbdBean.getData().getBusField().get(1).getBuschoices().get(i).getId() + "");
                }
            }
        }


            if (TextUtils.isEmpty(tjzlTextSssc.getText().toString())) {
                info.add("");
            } else {
                for (int i = 0; i < ywbdBean.getData().getBusField().get(2).getBuschoices().size(); i++) {
                    if (ywbdBean.getData().getBusField().get(2).getBuschoices().get(i).getTitle().equals(tjzlTextSssc.getText().toString())) {
                        info.add(ywbdBean.getData().getBusField().get(2).getBuschoices().get(i).getId() + "");
                    }
                }
            }

            if (TextUtils.isEmpty(tjzlTextSshy.getText().toString())) {
                info.add("");
            } else {
                for (int i = 0; i < ywbdBean.getData().getBusField().get(3).getBuschoices().size(); i++) {
                    if (ywbdBean.getData().getBusField().get(3).getBuschoices().get(i).getTitle().equals(tjzlTextSshy.getText().toString())) {
                        info.add(ywbdBean.getData().getBusField().get(3).getBuschoices().get(i).getId() + "");
                    }
                }
            }

            if (TextUtils.isEmpty(tjzlTextFmxx.getText().toString())) {
                info.add("");
            } else {
                for (int i = 0; i < ywbdBean.getData().getBusField().get(4).getBuschoices().size(); i++) {
                    if (ywbdBean.getData().getBusField().get(4).getBuschoices().get(i).getTitle().equals(tjzlTextFmxx.getText().toString())) {
                        info.add(ywbdBean.getData().getBusField().get(4).getBuschoices().get(i).getId() + "");
                    }
                }
            }


            info.add(tjzlEditZygs.getText().toString().trim());
            info.add(tjzlEditRzje.getText().toString().trim());
            info.add(tjzlEditZkl.getText().toString().trim());
            info.add(tjzlTextFksj.getText().toString().trim());
            info.add(tjzlEditRzqx.getText().toString().trim());
            info.add(tjzlEditLlyq.getText().toString().trim());
            info.add(tjzlEditLxr.getText().toString().trim());
            info.add(tjzlEditLxfs.getText().toString().trim());
            info.add(tjzlEditYq.getText().toString().trim());

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void yw_ci_show(final int i) {
        if (ywbdBean != null){
            BaseAdapter<YWBDBean.DataBean.BusFieldBean.BuschoicesBean> adapter = new BaseAdapter<YWBDBean.DataBean.BusFieldBean.BuschoicesBean>(this, ywbdBean.getData().getBusField().get(i).getBuschoices()) {
                @Override
                public void convert(int position, BaseViewHolder holder, YWBDBean.DataBean.BusFieldBean.BuschoicesBean bean) {
                    ((TextView)holder.getView(R.id.base_tjzl_popuwindow_text_item)).setText(bean.getTitle());
                }

                @Override
                public int getLayoutId(int viewType) {
                    return R.layout.view_popuwindow_base_tjzl_item;
                }
            };
            showPopupwindow(R.layout.view_popuwindow_base_tjzl, R.layout.ggpz_activity,adapter);
            adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    popWindow.dissmiss();
                    String info_view =((TextView)view.findViewById(R.id.base_tjzl_popuwindow_text_item)).getText().toString();
                    int id = -1;
                    /*for (BusinessBean.DataBean b : WecomeActivity.businessBean.getData()) {
                        if(info_view.equals(b.getTitle())){
                            id = b.getId();
                        }
                    }*/
                    switch (i){
                        case 1:
                            tjzlTextGpsx.setText(""+info_view);
                            break;
                        case 2:
                            tjzlTextSssc.setText(""+info_view);
                            break;
                        case 3:
                            tjzlTextSshy.setText(""+info_view);
                            break;
                        case 4:
                            tjzlTextFmxx.setText(""+info_view);
                            break;
                    }

                }
            });
        }
    }
}
